from _decimal import Decimal

from flask import render_template, jsonify, request, g, redirect, url_for, session

from models import db
from models.index import ShopCar, Product, Order
from utils.commons import get_order_code
from views import shop_bp


@shop_bp.route('/shopping_car')
def shopping_car():
    user = g.user
    if user:
        # 存放这个用户的所有加入购物车的商品信息并带着数量
        shop_car_list = []
        user_shop_product = db.session.query(ShopCar).filter(ShopCar.user_id == user.id).all()
        # 查询出购物车表内用户收藏的商品的信息和数量并存入列表
        for i in user_shop_product:
            product = db.session.query(Product).filter(Product.id == i.product_id).first()
            product.count = i.count
            shop_car_list.append(product)
        # 计算总价格
        price_all = 0
        for r in shop_car_list:
            every_price = float(r.price) * int(r.count)
            price_all += every_price
        price_all = Decimal(price_all).quantize(Decimal('0.00'))
        return render_template('shopping_cart.html', shop_car_list=shop_car_list, price_all=price_all, user=user,
                               shop_car_count=g.shop_car_count)
    else:
        return redirect(url_for('index.index'))


@shop_bp.route('/add_shop_car', methods=['POST'])
def add_shop_car():
    user = g.user
    product_id = request.json.get('product_id')
    count = request.json.get('count')

    if user:
        shop = db.session.query(ShopCar).filter(ShopCar.user_id == user.id, ShopCar.product_id == product_id).first()

        if shop:
            ret = {
                'errno': 7003,
                'errmsg': '该商品已经在购物车了'
            }
            return jsonify(ret)

        shop_car = ShopCar()
        shop_car.user_id = user.id
        shop_car.product_id = product_id
        shop_car.count = count
        try:
            db.session.add(shop_car)
            db.session.commit()

            ret = {
                'errno': 0,
                'errmsg': '成功'
            }
        except Exception as e:
            ret = {
                'errno': 7001,
                'errmsg': '添加失败'
            }
            return jsonify(ret)
    else:
        ret = {
            'errno': 7002,
            'errmsg': '请先登录'
        }

    return jsonify(ret)


@shop_bp.route('/remove_shop_car', methods=['POST'])
def remove_shop_car():
    user = g.user
    if user:
        product_id = request.json.get('product_id')
        shop_car = db.session.query(ShopCar).filter(ShopCar.product_id == product_id,
                                                    ShopCar.user_id == user.id).first()
        if shop_car:
            db.session.delete(shop_car)
            db.session.commit()
            ret = {
                'errno': 0,
                'errmsg': '删除成功'
            }
            return jsonify(ret)
        ret = {
            'errno': 7004,
            'errmsg': '当前商品已不在购物车'
        }
        return jsonify(ret)

    else:
        return redirect(url_for('index.index'))


@shop_bp.route('/order_form')
def order_form():
    user = g.user
    is_car = request.args.get('is_car')

    if user:
        product_id_list = session.get('product_id_list')
        shop_car_list = []
        for x, y in product_id_list.items():
            if x:
                product = db.session.query(Product).filter(Product.id == x).first()
                product.count = y
                shop_car_list.append(product)
        price_all = 0

        for i in shop_car_list:
            price_all += float(i.price) * int(i.count)
        price_all = Decimal(price_all).quantize(Decimal('0.00'))

        shop_address_list = user.shop_address

        return render_template('Orders.html', shop_car_list=shop_car_list, price_all=price_all,
                               shop_address_list=shop_address_list, user=user, is_car=is_car,
                               shop_car_count=g.shop_car_count)
    else:
        return redirect(url_for('index.index'))


@shop_bp.route('/if_pay', methods=['POST'])
def if_pay():
    user = g.user
    if user:
        product_id_list = request.json.get('product_id_list')
        # print(product_id_list)

        is_data = False
        for x, y in product_id_list.items():
            if x:
                is_data = True
        if is_data:
            session['product_id_list'] = product_id_list
            ret = {
                'errno': 0,
                'errmsg': '成功'
            }
        else:
            ret = {
                'errno': 7005,
                'errmsg': '你还没有选择要结算的商品'
            }
    else:
        ret = {
            'errno': 7006,
            'errmsg': '没有登录'
        }
    return jsonify(ret)


@shop_bp.route('/add_order', methods=['POST'])
def add_order():
    user = g.user
    if user:
        product_id_list = session.get('product_id_list')
        express = request.json.get('express')
        comment = request.json.get('comment')
        pay_money = request.json.get('pay_money')
        is_car = request.args.get('is_car')
        order_num = get_order_code()
        is_data = False
        for i in product_id_list:
            if i:
                is_data = True
        if is_data:
            order = Order()
            order.user_id = user.id
            order.product_id = str(product_id_list)
            order.express = express
            order.comment = comment
            order.pay_money = pay_money
            order.order_num = order_num
            db.session.add(order)
            db.session.commit()
            if is_car == 'yes':
                for x, y in product_id_list.items():
                    del_car = db.session.query(ShopCar).filter(ShopCar.user_id == user.id,
                                                               ShopCar.product_id == int(x)).first()
                    db.session.delete(del_car)
                    db.session.commit()
            ret = {
                'errno': 0,
                'errmsg': '成功'
            }
        else:
            ret = {
                'errno': 7007,
                'errmsg': '没有选择商品'
            }
        return jsonify(ret)
    else:
        return redirect(url_for('index.index'))
